import { DataService } from './../../services/data.service';
import { Component, OnInit, ViewEncapsulation, Input, OnDestroy } from '@angular/core';
import { RestService } from './../../services/rest.service';
import { ElasticsearchService } from './../../services/elasticsearch.service';
import { GridOptions } from 'ag-grid/main';
import { Subscription } from 'rxjs/Rx';

import * as _ from 'lodash';
import * as moment from 'moment';

@Component({
  selector: 'app-train-data-table',
  templateUrl: './train-data-table.component.html',
  styleUrls: ['./train-data-table.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class TrainDataTableComponent implements OnInit, OnDestroy {
  @Input() tableId: string;

  subscription: Subscription;

  gridOptions: GridOptions;
  columnDefs: any[];
  rowData: any[];

  constructor(public elastic: ElasticsearchService,
              public dataService: DataService,
              public restService: RestService) {
    this.subscription = this.dataService.data$.subscribe(event => {
      if (_.isString(event)) {
        // we don't handle events
        return;
      }

      this.rowData = this.adjustData(event);
    });
  }

  adjustData(row) {
    if (_.isArray(row)) {
      row.forEach(item => {
        item['train'] = '001';
        item[this.restService.timestamp] = this.restService.getUpdatedTime(item);
      });
    }

    return row;
  }

  /**
   * Grid API was included in params.
   */
  onGridReady(params) {
    // params.api.sizeColumnsToFit();
    if (this.elastic.lastRecord) {
      this.rowData = this.adjustData(this.elastic.lastRecord);
    }
  }

  selectAllRows() {
    this.gridOptions.api.selectAll();
  }

  /**
   * ngOnInit will be called before onGridReady, so it's ok
   * to initialize the grip options here.
   */
  ngOnInit() {
    this.gridOptions = this.restService.getGeneralGridOptions();
    this.columnDefs = this.restService.buildGridColumns(this.tableId);
    this.rowData = null;
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}
